<template>
  <div class="product-detail-container" v-loading="loading">
    <div class="product-breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/official/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/supply/prodinfo/purchindex' }">商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-row :gutter="20" class="product-main-content">
      <!-- 左侧图片展示 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="7">
        <div class="product-gallery">
          <div class="main-image-container">
            <el-carousel height="400px" indicator-position="none" ref="mainCarousel">
              <el-carousel-item v-for="(url, index) in imageList" :key="index">
                <el-image
                  :src="url"
                  fit="contain"
                  class="main-product-image"
                  :preview-src-list="imageList"
                >
                  <div slot="error" class="image-error">
                    <i class="el-icon-picture-outline-round"></i>
                    <span>图片加载失败</span>
                  </div>
                </el-image>
              </el-carousel-item>
            </el-carousel>
          </div>

          <div class="thumbnail-gallery">
            <div
              v-for="(url, index) in imageList"
              :key="index"
              class="thumbnail-item"
              :class="{ active: currentImageIndex === index }"
              @click="selectImage(index)"
            >
              <img :src="url" :alt="`${product.name} - 图片${index + 1}`"/>
            </div>
          </div>

          <div class="product-share">
            <el-button
              type="text"
              :class="{'is-collected': isCollected}"
              :icon="isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"
              @click="toggleCollect">
              {{ isCollected ? '已收藏' : '收藏商品' }}
            </el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" icon="el-icon-share">分享</el-button>
          </div>
        </div>
      </el-col>

      <!-- 中间商品信息 -->
      <el-col :xs="24" :sm="12" :md="10" :lg="10">
        <div class="product-info-panel">
          <h1 class="product-title">{{ product.name }}</h1>

          <div class="product-highlight">{{ product.remark || '优质商品，性价比高' }}</div>

          <div class="price-section">
            <div class="price-row">
              <span class="price-label">价格</span>
              <span class="price-value">
                <span class="currency">¥</span>
                <span class="amount">{{ product.unitPrice }}</span>
                <span class="unit">/ {{ product.minUnit }}</span>
              </span>
            </div>

            <div class="price-row">
              <span class="price-label">未税价格</span>
              <span class="untaxed-price">
                ¥ {{ (product.unitPrice / 1.13).toFixed(2) }}
                <span class="tax-rate">(税率: 13%)</span>
              </span>
            </div>

            <div class="price-ladder" v-if="product.unitPrice > 5">
              <div class="ladder-title">
                <i class="el-icon-discount"></i>
                <span>批量优惠</span>
              </div>
              <div class="ladder-content">
                <div class="ladder-item">
                  <span class="ladder-quantity">≥10{{ product.minUnit }}</span>
                  <span class="ladder-price">¥{{ (product.unitPrice * 0.98).toFixed(2) }}/{{ product.minUnit }}</span>
                </div>
                <div class="ladder-item">
                  <span class="ladder-quantity">≥30{{ product.minUnit }}</span>
                  <span class="ladder-price">¥{{ (product.unitPrice * 0.95).toFixed(2) }}/{{ product.minUnit }}</span>
                </div>
                <div class="ladder-item">
                  <span class="ladder-quantity">≥50{{ product.minUnit }}</span>
                  <span class="ladder-price">¥{{ (product.unitPrice * 0.92).toFixed(2) }}/{{ product.minUnit }}</span>
                </div>
              </div>
            </div>
          </div>

          <div class="product-attributes">
            <div class="attribute-row">
              <span class="attribute-label">品牌名称</span>
              <span class="attribute-value">
                <a href="javascript:;" class="brand-link">{{ product.brand }}</a>
              </span>
            </div>
            <div class="attribute-row">
              <span class="attribute-label">商品型号</span>
              <span class="attribute-value">{{ getTypeLabel(product.type) }}</span>
            </div>
            <div class="attribute-row">
              <span class="attribute-label">订货编码</span>
              <span class="attribute-value">{{ product.id }} <i class="el-icon-document-copy copy-icon"></i></span>
            </div>
            <div class="attribute-row">
              <span class="attribute-label">最小包装量</span>
              <span class="attribute-value">{{ product.minUnit || 1 }}</span>
            </div>
          </div>

          <div class="delivery-info">
            <div class="delivery-row">
              <span class="delivery-label">配送至</span>
              <span class="delivery-value">
                <span class="delivery-area">
                  <i class="el-icon-location"></i>
                  <span>河南省 焦作市</span>
                  <i class="el-icon-arrow-down"></i>
                </span>
                <span class="delivery-divider">|</span>
                <span class="freight-info">
                  运费
                  <span class="freight-detail">满300元包邮</span>
                  <el-tooltip placement="bottom">
                    <div slot="content">
                      <div>0元≤订单金额 &lt;300元,运费8元</div>
                      <div>订单金额满300元,免运费</div>
                    </div>
                    <span class="view-more">查看</span>
                  </el-tooltip>
                </span>
              </span>
            </div>

            <div class="delivery-row">
              <span class="delivery-label">发货日</span>
              <span class="delivery-value">
                <span class="stock-info">库存充足，48小时内发货</span>
              </span>
            </div>

            <div class="delivery-row">
              <span class="delivery-label">服务保障</span>
              <span class="delivery-value">
                <ul class="service-tags">
                  <li><i class="el-icon-check"></i> 正品保障</li>
                  <li><i class="el-icon-document"></i> 增票速开</li>
                  <li><i class="el-icon-service"></i> 售后保障</li>
                </ul>
              </span>
            </div>
          </div>

          <div class="purchase-actions">
            <div class="quantity-selector">
              <span class="quantity-label">购买数量：</span>
              <el-input-number
                v-model="purchaseQuantity"
                :min="1"
                :max="product.stockQuantity || 999"
                size="medium"
              ></el-input-number>
              <span class="unit-text">{{ product.minUnit }}</span>
            </div>

            <div class="total-price">
              总价：<span class="price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>

            <div class="action-buttons">
              <el-button v-if="!isSupplier" type="primary" icon="el-icon-shopping-cart-2" @click="addToCart">加入购物车</el-button>
              <el-button v-if="!isSupplier" type="danger" icon="el-icon-sold-out" @click="handleDirectOrder">立即购买</el-button>
              <el-button v-else type="info" disabled>无法购买自己的商品</el-button>
            </div>
          </div>
        </div>
      </el-col>

      <!-- 右侧推荐区域 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="7" class="right-sidebar">
<!--        <el-card class="supplier-card">-->
<!--          <div slot="header" class="supplier-header">-->
<!--            <span>供应商信息</span>-->
<!--          </div>-->
<!--          <div class="supplier-info">-->
<!--            <div class="supplier-logo">-->
<!--              <img :src="defaultImage" alt="供应商logo">-->
<!--            </div>-->
<!--            <div class="supplier-name">{{ product.supplierName || '优质供应商' }}</div>-->
<!--            <div class="supplier-stats">-->
<!--              <div class="stat-item">-->
<!--                <span class="stat-value">98%</span>-->
<!--                <span class="stat-label">好评率</span>-->
<!--              </div>-->
<!--              <div class="stat-item">-->
<!--                <span class="stat-value">24h</span>-->
<!--                <span class="stat-label">响应时间</span>-->
<!--              </div>-->
<!--              <div class="stat-item">-->
<!--                <span class="stat-value">99%</span>-->
<!--                <span class="stat-label">按时发货</span>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </el-card>-->

        <el-card class="similar-products">
          <div slot="header" class="similar-header">
            <span>同类商品推荐</span>
          </div>
          <div class="similar-list-container">
            <div v-for="item in similarProducts" :key="item.id"
                 class="similar-item"
                 @click="handleProductClick(item.id)">
              <el-image :src="item.imageUrl || defaultImage" fit="cover" class="similar-image">
                <template #error>
                  <div class="image-error">暂无图片</div>
                </template>
              </el-image>
              <div class="similar-info">
                <div class="similar-name">{{ item.name }}</div>
                <div class="similar-price">{{ formatPrice(item.unitPrice) }}</div>
              </div>
            </div>
            <div v-if="noMore" class="no-more">
              没有更多数据了
            </div>
          </div>
        </el-card>

        <el-card class="buyers-list" v-loading="loadingBuyers">
          <div slot="header" class="buyers-header">
            <span>最近购买</span>
          </div>
          <div class="buyer-items-container">
            <div v-for="(item, index) in recentBuyers" :key="index" class="buyer-item">
              <div class="buyer-info">
                <div class="buyer-header">
                  <el-avatar :size="36" class="buyer-avatar">
                    {{ item.companyName ? item.companyName.substr(0, 1) : 'A' }}
                  </el-avatar>
                  <div class="buyer-detail">
                    <div class="company-name">{{ item.companyName }}</div>
                    <div class="purchase-time">{{ item.purchaseTime }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-if="!loadingBuyers && recentBuyers.length === 0" class="no-data">
              暂无购买记录
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 商品详情选项卡 -->
    <div class="product-detail-tabs">
      <el-tabs type="border-card">
        <el-tab-pane label="商品介绍">
          <div class="detail-content">
            <div class="detail-section">
              <h3 class="section-title">产品特点</h3>
              <div class="section-content">
                <pre class="product-description">{{ product.remark || '暂无详细描述' }}</pre>
              </div>
            </div>

            <div class="detail-section">
              <h3 class="section-title">产品参数</h3>
              <div class="section-content">
                <el-descriptions border :column="2">
                  <el-descriptions-item label="商品名称">{{ product.name }}</el-descriptions-item>
                  <el-descriptions-item label="商品类型">
                    <dict-tag :options="dict.type.product_type" :value="product.type"/>
                  </el-descriptions-item>
                  <el-descriptions-item label="品牌">{{ product.brand }}</el-descriptions-item>
                  <el-descriptions-item label="规格单位">{{ product.minUnit }}</el-descriptions-item>
                  <el-descriptions-item label="商品性质">{{ product.nature || '普通商品' }}</el-descriptions-item>
                  <el-descriptions-item label="供应商">{{ product.supplierName }}</el-descriptions-item>
                  <el-descriptions-item label="库存数量">
                    <el-tag type="info">{{ product.stockQuantity || '充足' }}</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="单价">
                    <span class="price">{{ formatPrice(product.unitPrice) }}</span>
                  </el-descriptions-item>
                </el-descriptions>
              </div>
            </div>

            <div class="detail-section">
              <h3 class="section-title">商品图片</h3>
              <div class="detail-images">
                <div v-if="productIntroduceImages.length > 0" class="detail-image-group">
                  <h4>商品介绍图</h4>
                  <div v-for="(url, index) in productIntroduceImages" :key="'intro-'+index" class="detail-image-item">
                    <el-image
                      :src="url"
                      fit="contain"
                      :preview-src-list="productIntroduceImages"
                    ></el-image>
                  </div>
                </div>

                <div v-if="productParamImages.length > 0" class="detail-image-group">
                  <h4>商品参数图</h4>
                  <div v-for="(url, index) in productParamImages" :key="'param-'+index" class="detail-image-item">
                    <el-image
                      :src="url"
                      fit="contain"
                      :preview-src-list="productParamImages"
                    ></el-image>
                  </div>
                </div>

                <div v-if="productDetailImages.length > 0" class="detail-image-group">
                  <h4>商品详细图</h4>
                  <div v-for="(url, index) in productDetailImages" :key="'detail-'+index" class="detail-image-item">
                    <el-image
                      :src="url"
                      fit="contain"
                      :preview-src-list="productDetailImages"
                    ></el-image>
                  </div>
                </div>

                <div v-if="productApplyImages.length > 0" class="detail-image-group">
                  <h4>商品应用图</h4>
                  <div v-for="(url, index) in productApplyImages" :key="'apply-'+index" class="detail-image-item">
                    <el-image
                      :src="url"
                      fit="contain"
                      :preview-src-list="productApplyImages"
                    ></el-image>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="规格与包装">
          <div class="detail-content">
            <el-empty v-if="!product.nature" description="暂无规格与包装信息"></el-empty>
            <div v-else class="package-info">
              <div class="detail-section">
                <h3 class="section-title">包装规格</h3>
                <div class="section-content">
                  <p>{{ product.minUnit }} / 件</p>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="售后保障">
          <div class="detail-content">
            <div class="warranty-section">
              <div class="warranty-item">
                <h3><i class="el-icon-success"></i> 正品保证</h3>
                <p>本平台向您保证所售商品均为正品行货，本平台自营商品开具机打发票或电子发票。</p>
              </div>
              <div class="warranty-item">
                <h3><i class="el-icon-s-claim"></i> 全国联保</h3>
                <p>凭质保证书及本平台发票，可享受全国联保服务，与您亲临商场选购的商品享受相同的质量保证。</p>
              </div>
              <div class="warranty-item">
                <h3><i class="el-icon-warning"></i> 无忧退货</h3>
                <p>客户购买本平台自营商品，若经检测商品存在质量问题，可享受7天无理由退货。</p>
                <p>（注：部分商品除外，详情请咨询客服）</p>
              </div>
              <div class="warranty-item">
                <h3><i class="el-icon-s-cooperation"></i> 专业服务</h3>
                <p>专业的采购顾问和客服团队，为您提供一对一贴心服务。</p>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 购物车弹出组件 -->
    <cart-popup ref="cartPopup"
                :value="showCart"
                :cartItem="cartItem"
                :quantity.sync="purchaseQuantity"
                @input="showCart = $event">
    </cart-popup>

    <!-- 下订单对话框 -->
    <el-dialog
      title="订单确认"
      :visible.sync="orderVisible"
      width="500px"
      @close="handleOrderDialogClose"
      custom-class="order-dialog"
    >
      <div class="order-content">
        <div class="order-summary">
          <div class="summary-header">
            <span class="title">已选商品</span>
          </div>
          <div class="order-list-container">
            <div class="order-item">
              <div class="item-left">
                <el-image
                  :src="product.imageList ? product.imageList[0] : defaultImage"
                  fit="cover"
                  class="product-img"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div class="product-info">
                  <div class="product-name">{{ product.name }}</div>
                </div>
              </div>
              <div class="item-right">
                <div class="quantity">x{{ purchaseQuantity }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加地址选择部分 -->
        <div class="address-section">
          <!-- 判断角色用户可以选择添加审批流程模板，判断用户角色是否为purchaser-stratagem、purchaser-guarantor-->
          <div v-if="getUserRole">
            <el-button type="primary" size="mini" @click="openTemplateSelector">
              <i class="el-icon-s-check"></i> 选择审批流程
            </el-button>
            <div v-if="selectedTemplate" class="selected-template-info">
              <span>已选审批流程：</span>
              <el-tag type="success">{{ selectedTemplate.templateName }}</el-tag>
              <el-button type="text" size="mini" @click="removeTemplate">
                <i class="el-icon-close"></i> 移除
              </el-button>

              <!-- 添加审批流程详情回显 -->
              <div class="template-preview" v-if="templateDetail">
                <div class="template-info">
                  <div class="template-desc" v-if="selectedTemplate.templateDesc">
                    <span class="info-label">描述：</span>
                    <span>{{ selectedTemplate.templateDesc }}</span>
                  </div>
                  <div class="template-type">
                    <span class="info-label">类型：</span>
                    <span>{{ flowTypeFormat(selectedTemplate) }}</span>
                  </div>
                </div>
                <div class="nodes-preview">
                  <div class="nodes-title">
                    <i class="el-icon-s-operation"></i>
                    <span>审批节点</span>
                    <el-button type="text" size="mini" @click="previewTemplate">
                      <i class="el-icon-view"></i> 查看流程图
                    </el-button>
                  </div>
                  <div class="nodes-list">
                    <div v-for="(node, index) in templateDetail.nodes" :key="index" class="node-item">
                      <div class="node-number">{{ index + 1 }}</div>
                      <div class="node-content">
                        <div class="node-name">{{ node.nodeName }}</div>
                        <div class="node-details">
                          <span v-if="node.approvalRoles && node.approvalRoles.length">
                            <i class="el-icon-user"></i> 角色：{{ formatRoles(node.approvalRoles) }}
                          </span>
                          <span v-if="node.needSignature" class="signature-required">
                            <i class="el-icon-edit-outline"></i> 需要签名
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="section-header">
            <span class="title">收货地址</span>
            <el-button type="text" @click="showAddAddressDialog">新增地址</el-button>
          </div>

          <div class="address-list">
            <el-empty v-if="addressList.length === 0" description="暂无收货地址"></el-empty>
            <div v-else class="address-list-container">


              <el-radio-group v-model="selectedAddressId" class="address-radio-group">

                <el-radio
                  v-for="addr in addressList"
                  :key="addr.id"
                  :label="addr.id"
                  class="address-radio-item">
                  <div class="address-info">

                    <div class="address-tag">
                      <el-tag
                        size="small"
                        :type="addr.userName === '默认地址' ? 'success' : 'primary'"
                      >
                        {{ addr.userName }}
                      </el-tag>

                      <span class="area-tag">{{ addr.areaLabel }}</span>

                    </div>

                    <div class="address-main">{{ addr.address }}</div>
                    <div class="address-time">
                      <i class="el-icon-time"></i>
                      {{ addr.createTime }}
                    </div>
                  </div>
                </el-radio>


              </el-radio-group>
            </div>
          </div>
        </div>

        <div class="order-footer">
          <div class="total-info">
            <div class="total-item">
              <span class="label">商品数量：</span>
              <span class="value">{{ purchaseQuantity }}件</span>
            </div>
            <div class="total-item">
              <span class="label">商品总价：</span>
              <span class="value price">¥{{ totalPrice.toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="orderVisible = false">取消</el-button>
          <el-button type="danger" @click="handleAbandonOrder">下单</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增地址弹窗 -->
    <el-dialog
      title="新增收货地址"
      :visible.sync="addAddressVisible"
      width="500px"
      append-to-body
      :before-close="handleAddressDialogClose"
    >
      <el-form :model="addressForm" ref="addressForm" :rules="addressRules" label-width="100px">
        <el-form-item label="地址标签" prop="userName">
          <el-input
            v-model="addressForm.userName"
            placeholder="请输入地址标签，如：家、公司、学校"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>

        <el-form-item label="区域" prop="area">
          <el-select v-model="addressForm.area" placeholder="请选择区域" clearable style="width: 100%">
            <el-option
              v-for="dict in dict.type.address_area"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所在地区" prop="address">
          <el-cascader
            v-model="selectedRegion"
            :options="regionData"
            :props="{
              expandTrigger: 'hover',
              value: 'label',
              label: 'label',
              children: 'children'
            }"
            @change="handleAddressChange"
            placeholder="请选择省/市/区/街道"
            style="width: 100%"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input
            v-model="addressForm.address"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址，如：街道、门牌号等"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addAddressVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddress">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审批模板选择组件 -->
    <template-selector
      :visible.sync="templateSelectorVisible"
      :productId="product.id"
      @select="handleTemplateSelect"
      @close="handleSelectorClose"
      ref="templateSelector"
    />
  </div>
</template>

<script>
import {getProdinfo, listProdinfo, recentPurchase, getProdinfoPro} from "@/api/supply/prodinfo";
import CartPopup from './CartPopup.vue';
import {getCustomerId} from "@/api/supply/purchcar";
import {addOrder} from "@/api/supply/psorders";
import {getUserProfile} from "@/api/system/user";
import {selectByUserId, addAddress} from "@/api/supply/address";
import {mapGetters} from 'vuex';
import defaultImage from '@/assets/images/product1.jpg';
import {getDicts} from "@/api/system/dict/data";
import TemplateSelector from '@/views/supply/prodinfo/TemplateSelector';

import request from '@/utils/request';
import {listRole} from "@/api/system/role"; // 添加请求模块

// 添加收藏API方法
function collectProduct(id) {
  return request({
    url: `/supply/book/${id}`,
    method: 'put'
  });
}

// 获取收藏状态API方法
function getCollectionStatusAPI(id) {
  return request({
    url: `/supply/book/status/${id}`,
    method: 'get'
  });
}

export default {
  name: "ProductDetail",
  dicts: ['product_type', 'product_status', 'address_area'],
  components: {
    CartPopup,
    TemplateSelector
  },

  data() {
    return {
      areaOptions: [],
      loading: true,
      loadingBuyers: false,
      defaultImage: defaultImage,
      product: {},
      imageList: [],
      productIntroduceImages: [], // 商品介绍图片
      productParamImages: [],     // 商品参数图片
      productDetailImages: [],    // 商品详细图片
      productApplyImages: [],     // 商品应用图片
      showCart: false,
      cartItem: {},
      purchaseQuantity: 1,
      orderVisible: false,
      currentImageIndex: 0,
      similarProducts: [],
      recentBuyers: [],
      noMore: false,
      addAddressVisible: false,
      addressList: [],
      selectedAddressId: null,
      addressForm: {
        address: '', // 只存储详细地址
        userId: '',
        userName: '',
        area: ''
      },
      addressRules: {
        userName: [
          {required: true, message: '请输入地址标签', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur'}
        ],
        area: [
          {required: true, message: "区域不能为空", trigger: "change"}
        ],
        address: [
          {required: true, message: '请输入完整地址', trigger: 'blur'}
        ]
      },
      user: {},
      templateId: null,
      selectedTemplate: null,
      isCollected: false, // 添加收藏状态属性
      templateDetail: null,
      templateSelectorVisible: null,
      discountRate: 1, // 新增折扣率字段，默认为1
      isSupplier: false, // 新增字段，默认为 false
      regionData: [
        {
          value: '河南省',
          label: '河南省',
          children: [
            {
              value: '焦作市',
              label: '焦作市',
              children: [
                {
                  value: '解放区',
                  label: '解放区',
                  children: [
                    { value: '民主街道', label: '民主街道' },
                    { value: '民生街道', label: '民生街道' }
                  ]
                },
                {
                  value: '中站区',
                  label: '中站区',
                  children: [
                    { value: '许衡街道', label: '许衡街道' },
                    { value: '李封街道', label: '李封街道' }
                  ]
                }
              ]
            }
          ]
        }
      ],
      selectedRegion: [], // 用于存储级联选择器的值
      regionText: '', // 新增：用于存储所在地区的文本
    }
  },
  computed: {


    ...mapGetters([
      'name',
      'userId'
    ]),
    totalPrice() {
      return this.purchaseQuantity * (this.product.unitPrice || 0) * this.discountRate;
    }
  },
  created() {
    this.getDetail();
    this.getUser();
    this.getCollectionStatus();
    this.getUserRole();
    this.getRegionData(); // 获取省市区数据
  },
  methods: {

    selectImage(index) {
      this.currentImageIndex = index;
      this.$refs.mainCarousel.setActiveItem(index);
    },

    getDetail() {
      this.loading = true;
      getProdinfoPro(this.$route.params.productId).then(response => {
        this.product = response.data;
        console.log("商品详情", this.product);

        // 处理商品主图片列表
        if (this.product.imageUrl) {
          this.imageList = this.product.imageUrl.split(',');
        } else {
          this.imageList = [this.defaultImage];
        }

        // 处理商品详情图片
        this.processDetailImages();

        // 如果商品已关联模板，则获取模板信息
        if (this.product.templateId) {
          this.getTemplateDetail(this.product.templateId);
        }

        this.loading = false;
        this.getRecentPurchases();
        this.getSimilarList();

        // 在获取商品详情后，再获取收藏状态
        this.getCollectionStatus();

        // 在获取商品信息后检查权限
        if (this.user) {
          this.checkSupplierPermission();
        }
      }).catch(error => {
        this.$message.error('获取商品详情失败：' + error.message);
        this.loading = false;
      });
    },

    // 处理商品详情图片
    processDetailImages() {
      // 处理商品介绍图片
      if (this.product.prodIntroduceImgUrls) {
        this.productIntroduceImages = this.product.prodIntroduceImgUrls.split(',');
      } else {
        this.productIntroduceImages = [];
      }

      // 处理商品参数图片
      if (this.product.prodParamImgUrls) {
        this.productParamImages = this.product.prodParamImgUrls.split(',');
      } else {
        this.productParamImages = [];
      }

      // 处理商品详情图片
      if (this.product.prodDetailImgUrls) {
        this.productDetailImages = this.product.prodDetailImgUrls.split(',');
      } else {
        this.productDetailImages = [];
      }

      // 处理商品应用图片
      if (this.product.prodApplyImgUrls) {
        this.productApplyImages = this.product.prodApplyImgUrls.split(',');
      } else {
        this.productApplyImages = [];
      }
    },

    getSimilarList() {
      const queryParams = {
        pageNum: 1,
        pageSize: 8,
        type: this.product.type,
        status: 1
      };

      listProdinfo(queryParams).then(response => {
        // 过滤掉当前商品
        this.similarProducts = response.rows.filter(item => item.id !== this.product.id);

        // 如果同类商品不足5个，随机添加库存
        if (this.similarProducts.length < 5) {
          this.noMore = true;
        } else {
          this.noMore = false;
        }
      }).catch(error => {
        console.error('获取同类商品失败', error);
      });
    },

    formatPrice(price) {
      return `￥${Number(price).toFixed(2)}`;
    },

    addToCart() {
      if (this.isSupplier) {
        this.$message.warning('无法购买自己的商品');
        return;
      }
      this.cartItem = this.product;
      this.showCart = true;
    },

    handleDirectOrder() {
      if (this.isSupplier) {
        this.$message.warning('无法购买自己的商品');
        return;
      }
      if (this.purchaseQuantity > (this.product.stockQuantity || 999)) {
        this.$message.error('购买数量不能大于库存数量');
        return;
      }
      this.getAddressList();
      this.orderVisible = true;
    },

    handleOrderDialogClose() {
      // 关闭订单对话框时的处理
    },

    handleAbandonOrder() {
      if (!this.selectedAddressId) {
        this.$message.warning('请选择收货地址');
        return;
      }

      // 获取模板ID前先检查模板对象
      // const templateId = this.selectedTemplate && this.selectedTemplate.id ? this.selectedTemplate.id : null;

      console.log('下单时使用的模板ID:', this.templateId);
      const orderData = {
        addressId: this.selectedAddressId,
        productId: this.product.id,
        supplierId: this.product.supplierId,
        customerId: this.user.userId,
        orderAmount: this.totalPrice, // 使用计算后的总价
        paymentMethod: '在线支付',
        orderDate: new Date().toISOString().split('T')[0],
        orderStatus: "1",
        quantity: this.purchaseQuantity,
        templateId: this.templateId
      };
      console.log("下单数据", orderData);

      // 显示加载状态
      const loading = this.$loading({
        lock: true,
        text: '订单提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.8)'
      });

      addOrder(orderData).then(response => {
        loading.close();
        this.$modal.msgSuccess('下单成功');
        this.orderVisible = false;

        // 显示确认对话框，询问用户是否要跳转到订单页面
        this.$confirm('下单成功！是否前往订单管理页面查看？', '操作成功', {
          confirmButtonText: '前往查看',
          cancelButtonText: '留在当前页面',
          type: 'success'
        }).then(() => {
          // 用户点击了"前往查看"，直接跳转到订单管理页面
          this.$router.push({name: 'PersonOrders'}).catch(err => {
            console.error('跳转到订单页面失败:', err);
            this.$message.info('无法自动跳转到订单页面，请从菜单手动进入订单管理');
          });
        }).catch(() => {
          // 用户点击了"留在当前页面"，不执行任何操作
          console.log('用户选择留在当前页面');
        });
      }).catch(error => {
        loading.close();
        this.$message.error('下单失败：' + (error.msg || error.message));
      });
    },

    handleProductClick(productId) {
      this.$router.push(`/supply/prodinfo/${productId}`);
    },

    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        console.log("用户信息", this.user);
        // 在获取用户信息后检查权限
        if (this.product) {
          this.checkSupplierPermission();
        }
      }).catch(error => {
        console.error('获取用户信息失败', error);
      });
    },

    getRecentPurchases() {
      this.loadingBuyers = true;
      if (!this.product.id) {
        this.loadingBuyers = false;
        return;
      }

      recentPurchase(this.product.id).then(response => {
        const purchaseList = response.data || [];
        this.recentBuyers = purchaseList.map(item => {
          const [companyName, timeInfo] = item.split('   ');
          return {
            companyName: companyName || '匿名企业',
            purchaseTime: timeInfo || '近期'
          };
        });
      }).catch(error => {
        console.error('获取最近购买记录失败', error);
      }).finally(() => {
        this.loadingBuyers = false;
      });
    },

    // 获取用户地址列表
    // async getAddressList() {
    //   try {
    //     if (!this.user.userId) {
    //       return;
    //     }
    //     const response = await selectByUserId(this.user.userId);
    //     if (response.code === 200) {
    //       this.addressList = response.rows || [];
    //       if (this.addressList.length > 0 && !this.selectedAddressId) {
    //         this.selectedAddressId = this.addressList[0].id;
    //       }
    //     } else {
    //       this.$message.error(response.msg || '获取地址列表失败');
    //     }
    //   } catch (error) {
    //     this.$message.error('获取地址列表失败：' + error.message);
    //   }
    // },
    async getAddressList() {
      try {
        if (!this.user.userId) return;
        const response = await selectByUserId(this.user.userId);
        if (response.code !== 200) {
          this.$message.error(response.msg || '获取地址列表失败');
          return;
        }
        // 添加区域字典映射处理
        this.addressList = (response.rows || []).map(address => {
          const areaDictItem = this.dict.type.address_area.find(
            item => item.value === address.area
          );

          return {
            ...address,
            // 添加 areaLabel 字段
            areaLabel: areaDictItem ? areaDictItem.label : '未知区域'
          };
        });

        // 自动选择第一个地址
          if (this.addressList.length > 0 && !this.selectedAddressId) {
            this.selectedAddressId = this.addressList[0].id;
        }
      } catch (error) {
        this.$message.error('获取地址列表失败：' + error.message);
      }
    },

    // 显示新增地址弹窗
    showAddAddressDialog() {
      this.selectedRegion = [];
      this.regionText = ''; // 重置所在地区文本
      this.addressForm = {
        address: '',
        userId: this.user.userId,
        userName: '',
        area: ''
      };
      this.addAddressVisible = true;
    },

    // 处理地址选择变化
    handleAddressChange(value) {
      if (value && value.length > 0) {
        // 只更新所在地区的文本，不影响详细地址
        this.regionText = value.join(' ');
      }
    },

    // 提交新增地址
    submitAddress() {
      this.$refs.addressForm.validate(async (valid) => {
        if (valid) {
          try {
            // 提交时组合所在地区和详细地址
            const fullAddress = this.regionText ? `${this.regionText} ${this.addressForm.address}` : this.addressForm.address;

            const addressData = {
              userId: this.user.userId,
              userName: this.addressForm.userName,
              area: this.addressForm.area,
              address: fullAddress
            };
            await addAddress(addressData);
            this.$message.success('添加地址成功');
            this.addAddressVisible = false;
            await this.getAddressList();
          } catch (error) {
            this.$message.error('添加地址失败：' + error.message);
          }
        }
      });
    },
    openTemplateSelector() {
      this.templateSelectorVisible = true;
    },

    handleTemplateSelect(template) {
      console.log('选择的模板原始数据:', template);

      // 防止模板不存在
      if (!template) {
        this.$message.warning('未选择有效的审批流程模板');
        return;
      }

      // 确保有模板ID
      if (!template.id) {
        console.error('模板缺少ID:', template);
        this.$message.error('选择的模板无效，请重新选择');
        return;
      }

      // 保存模板对象和ID
      this.selectedTemplate = template;
      this.templateId = template.id;

      console.log('已选择审批流程模板:', this.templateId, template.templateName);

      // 解析流程节点数据
      this.parseTemplateNodes(template);
    },

    // 添加解析模板节点的专门方法
    parseTemplateNodes(template) {
      if (!template) return;

      // 检查是否已有processNodes数据
      if (template.processNodes) {
        try {
          this.templateDetail = JSON.parse(template.processNodes);
          console.log("成功解析模板节点数据:", this.templateDetail);
        } catch (e) {
          console.error("解析模板节点数据失败:", e);
          this.templateDetail = null;

          // 如果解析失败，尝试通过API重新获取完整数据
          this.getTemplateDetail(template.id);
        }
      } else {
        console.log("模板缺少流程节点数据，尝试从API获取");
        // 如果模板对象中没有流程节点数据，尝试从API获取
        this.getTemplateDetail(template.id);
      }
    },

    // 处理模板选择器关闭事件
    handleSelectorClose() {
      // 如果已选择了模板，则保留选择结果，否则清除
      if (!this.selectedTemplate) {
        this.templateDetail = null;
        this.templateId = null;
      }
    },

    // 移除已选择的模板
    removeTemplate() {
      this.$confirm('确认移除已选审批流程模板吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const previousTemplateId = this.selectedTemplate ? this.selectedTemplate.id : null;
        this.selectedTemplate = null;
        this.templateDetail = null;  // 清除模板详情数据
        this.templateId = null;      // 清除模板ID
        this.$message.success('已移除审批流程模板');
      }).catch(() => {
        // 用户取消操作
      });
    },

    // 修改获取模板详情的方法
    getTemplateDetail(templateId) {
      if (!templateId) {
        console.error("无效的模板ID");
        return;
      }

      console.log("从API获取模板详情:", templateId);

      // 显示加载提示
      const loading = this.$loading({
        lock: true,
        text: '正在加载模板数据...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.7)'
      });

      import('@/api/supply/template').then(module => {
        const {getTemplate} = module;
        getTemplate(templateId).then(response => {
          loading.close();

          if (response.code === 200 && response.data) {
            // 更新模板对象
            this.selectedTemplate = response.data;
            // 更新模板ID
            this.templateId = response.data.id;

            console.log("已加载完整模板信息:", this.selectedTemplate);

            // 解析流程节点数据
            if (this.selectedTemplate.processNodes) {
              try {
                this.templateDetail = JSON.parse(this.selectedTemplate.processNodes);
                console.log("模板节点数据:", this.templateDetail);
              } catch (e) {
                console.error("解析模板节点数据失败:", e);
                this.$message.error('模板数据格式异常，无法显示流程节点');
                this.templateDetail = null;
              }
            } else {
              console.error("API返回的模板数据没有processNodes字段");
              this.$message.warning('模板数据不完整，无法显示流程节点');
              this.templateDetail = null;
            }
          } else {
            console.error("获取模板API返回异常:", response);
            this.$message.error('获取模板详情失败');
          }
        }).catch(error => {
          loading.close();
          console.error("获取模板详情API调用失败:", error);
          this.$message.error('获取模板详情失败: ' + (error.message || '未知错误'));
        });
      }).catch(error => {
        loading.close();
        console.error("导入模板API模块失败:", error);
        this.$message.error('系统错误，无法加载模板功能');
      });
    },

    // 添加审批流程类型翻译方法
    flowTypeFormat(template) {
      if (!template || !template.flowType) return '未知类型';
      const flowTypes = {
        'purchase': '采购审批',
        'sales': '销售审批',
        'hr': '人事审批',
        'finance': '财务审批',
        'other': '其他审批'
      };
      return flowTypes[template.flowType] || template.flowType;
    },

    // 添加格式化审批角色方法
    formatRoles(roleKeys) {
      if (!roleKeys || !roleKeys.length) return '无';
      return roleKeys.join(', ');
    },

    // 添加预览模板流程图方法
    previewTemplate() {
      // 打开模板选择器的预览功能
      if (this.selectedTemplate) {
        this.templateSelectorVisible = true;
        // 使用nextTick确保模板选择器组件已加载
        this.$nextTick(() => {
          // 通过ref获取子组件实例并调用其预览方法
          const selector = this.$refs.templateSelector;
          if (selector) {
            selector.handlePreview(this.selectedTemplate);
          }
        });
      }
    },

    // 切换收藏状态
    toggleCollect() {
      if (!this.product.id) {
        this.$message.warning('商品信息不完整，无法收藏');
        return;
      }

      // 先切换UI状态，提供即时反馈
      const prevState = this.isCollected;
      this.isCollected = !this.isCollected;

      collectProduct(this.product.id).then(response => {
        if (response.code === 200) {
          this.$message.success(this.isCollected ? '收藏成功' : '已取消收藏');
        } else {
          // 如果操作失败，恢复原状态
          this.isCollected = prevState;
          this.$message.error(response.msg || '操作失败');
        }
      }).catch(error => {
        // 如果请求出错，恢复原状态
        this.isCollected = prevState;
        console.error('收藏操作失败', error);
        this.$message.error('操作失败，请稍后再试');
      });
    },

    // 获取收藏状态
    getCollectionStatus() {
      if (!this.product.id) return;

      getCollectionStatusAPI(this.product.id).then(response => {
        if (response.code === 200) {
          // 如果返回值为1，则表示已收藏，否则未收藏
          this.isCollected = response.data === 1;
        }
      }).catch(error => {
        console.error('获取收藏状态失败', error);
        // 发生错误时默认为未收藏
        this.isCollected = false;
      });
    },


    // 获取用户角色
    getUserRole() {
      // 默认返回true以便于测试
      let hasRequiredRole = true;

      try {
        // 从vuex中获取用户角色
        console.log("检查用户角色权限");

        // 使用includes方法替代错误的contains方法
        listRole().then((res) => {
          console.log("获取到角色列表:", res);
          if (res && res.rows && Array.isArray(res.rows)) {
            // 查找是否有匹配的角色
            const matchedRole = res.rows.find(item =>
              item.roleKey && (
                item.roleKey.includes("admin") ||
                item.roleKey.includes("purchaser-stratagem") ||
                item.roleKey.includes("purchaser-guarantor")
              )
            );

            hasRequiredRole = !!matchedRole;
            console.log("用户是否有审批权限:", hasRequiredRole);
          } else {
            console.warn("角色数据异常:", res);
          }
        }).catch(error => {
          console.error("获取角色列表失败:", error);
        });

      } catch (error) {
        console.error("角色检查出错:", error);
      }

      // 返回默认值，保证UI渲染正常
      return hasRequiredRole;
    },
    getTypeLabel(typeId) {
      if (!typeId) return '';
      const dict = this.dict && this.dict.type && this.dict.type.product_type;
      if (!dict) return typeId;
      const found = dict.find(item => String(item.value) === String(typeId));
      return found ? found.label : typeId;
    },
    checkSupplierPermission() {
      console.log('检查供应商权限', {
        userId: this.user?.userId,
        supplierId: this.product?.supplierId,
        isSupplier: this.isSupplier
      });

      // 确保用户和商品信息都已加载
      if (!this.user || !this.product) {
        console.log('用户或商品信息未加载完成，暂不进行权限检查');
        this.isSupplier = false;
        return;
      }

      // 只有当用户是当前商品的供应商时才禁止购买
      if (this.user.userId === this.product.supplierId) {
        this.isSupplier = true;
        console.log('当前用户是商品供应商，禁止购买自己的商品');
      } else {
        this.isSupplier = false;
        console.log('当前用户可以购买此商品');
      }
    },
    // 获取省市区数据
    getRegionData() {
      // 这里使用 Element UI 内置的中国省市区数据
      import('element-china-area-data').then(module => {
        this.regionData = module.regionData;
      });
    },
    handleAddressDialogClose(done) {
      this.selectedRegion = [];
      this.regionText = ''; // 重置所在地区文本
      this.addressForm = {
        address: '',
        userId: this.user.userId,
        userName: '',
        area: ''
      };
      if (this.$refs.addressForm) {
        this.$refs.addressForm.resetFields();
      }
      done();
    },
  },

  // 在 methods 后添加 watch 配置
  watch: {
    purchaseQuantity(newVal) {
      if (newVal >= 50) {
        this.discountRate = 0.92;
      } else if (newVal >= 30) {
        this.discountRate = 0.95;
      } else if (newVal >= 10) {
        this.discountRate = 0.98;
      } else {
        this.discountRate = 1;
      }
    }
  },

};
</script>

<style lang="scss" scoped>
.product-detail-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  .product-breadcrumb {
    margin-bottom: 15px;
    padding: 8px 0;
  }

  .product-main-content {
    margin-bottom: 20px;

    .product-gallery {
      background: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
      padding: 15px;
      margin-bottom: 20px;

      .main-image-container {
        height: 400px;
        margin-bottom: 15px;
        border: 1px solid #ebeef5;
        overflow: hidden;

        .main-product-image {
          width: 100%;
          height: 100%;

          &::v-deep .el-image__inner {
            transition: transform 0.3s;

            &:hover {
              transform: scale(1.05);
            }
          }
        }
      }

      .thumbnail-gallery {
        display: flex;
        flex-wrap: nowrap;
        overflow-x: auto;
        margin-bottom: 15px;
        padding-bottom: 5px;

        &::-webkit-scrollbar {
          height: 5px;
        }

        &::-webkit-scrollbar-thumb {
          background: #dcdfe6;
          border-radius: 3px;
        }

        .thumbnail-item {
          width: 70px;
          height: 70px;
          margin-right: 10px;
          cursor: pointer;
          border: 2px solid transparent;
          overflow: hidden;
          flex-shrink: 0;

          &.active {
            border-color: #409EFF;
          }

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }

          &:hover img {
            transform: scale(1.05);
          }
        }
      }

      .product-share {
        display: flex;
        justify-content: center;
        align-items: center;
        padding-top: 10px;
        border-top: 1px solid #ebeef5;

        .el-button {
          font-size: 13px;
          transition: all 0.3s;

          &.is-collected {
            color: #E6A23C; /* 黄色 */
          }

          .el-icon-star-on {
            color: #E6A23C; /* 黄色 */
          }
        }
      }
    }

    .product-info-panel {
      background: #fff;
      border-radius: 4px;
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
      padding: 20px;
      height: 100%;

      .product-title {
        font-size: 18px;
        color: #303133;
        margin: 0 0 15px 0;
        line-height: 1.4;
        font-weight: 600;
      }

      .product-highlight {
        color: #909399;
        font-size: 14px;
        margin-bottom: 20px;
        line-height: 1.5;
      }

      .price-section {
        margin-bottom: 20px;
        padding: 15px 0;
        border-top: 1px dashed #ebeef5;
        border-bottom: 1px dashed #ebeef5;

        .price-row {
          display: flex;
          align-items: center;
          margin-bottom: 10px;

          .price-label {
            width: 80px;
            color: #606266;
            font-size: 14px;
          }

          .price-value {
            color: #F56C6C;
            font-size: 16px;

            .currency {
              font-size: 14px;
              font-weight: normal;
            }

            .amount {
              font-size: 24px;
              font-weight: bold;
            }

            .unit {
              font-size: 14px;
              color: #909399;
              margin-left: 5px;
            }
          }

          .untaxed-price {
            color: #606266;
            font-size: 14px;

            .tax-rate {
              color: #909399;
              margin-left: 5px;
            }
          }
        }

        .price-ladder {
          margin-top: 15px;

          .ladder-title {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            color: #606266;
            font-size: 14px;

            i {
              color: #E6A23C;
              margin-right: 5px;
              font-size: 16px;
            }
          }

          .ladder-content {
            display: flex;
            background: #f8f9fa;
            border-radius: 4px;
            padding: 10px;

            .ladder-item {
              flex: 1;
              text-align: center;
              padding: 0 5px;
              border-right: 1px dashed #dcdfe6;

              &:last-child {
                border-right: none;
              }

              .ladder-quantity {
                display: block;
                font-size: 13px;
                color: #606266;
                margin-bottom: 5px;
              }

              .ladder-price {
                display: block;
                font-size: 14px;
                color: #F56C6C;
                font-weight: bold;
              }
            }
          }
        }
      }

      .product-attributes {
        margin-bottom: 20px;

        .attribute-row {
          display: flex;
          margin-bottom: 12px;
          font-size: 14px;

          .attribute-label {
            width: 80px;
            color: #606266;
          }

          .attribute-value {
            color: #303133;

            .brand-link {
              color: #409EFF;
              text-decoration: none;

              &:hover {
                text-decoration: underline;
              }
            }

            .copy-icon {
              margin-left: 5px;
              color: #909399;
              cursor: pointer;

              &:hover {
                color: #409EFF;
              }
            }
          }
        }
      }

      .delivery-info {
        background: #f8f9fa;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 20px;

        .delivery-row {
          display: flex;
          margin-bottom: 12px;
          font-size: 14px;

          &:last-child {
            margin-bottom: 0;
          }

          .delivery-label {
            width: 80px;
            color: #606266;
          }

          .delivery-value {
            color: #303133;

            .delivery-area {
              display: inline-flex;
              align-items: center;
              cursor: pointer;

              i {
                margin-right: 5px;

                &.el-icon-arrow-down {
                  font-size: 12px;
                  margin-left: 5px;
                  color: #909399;
                }
              }

              &:hover {
                color: #409EFF;
              }
            }

            .delivery-divider {
              margin: 0 10px;
              color: #dcdfe6;
            }

            .freight-info {
              color: #606266;

              .freight-detail {
                margin: 0 5px;
                color: #303133;
              }

              .view-more {
                color: #409EFF;
                cursor: pointer;

                &:hover {
                  text-decoration: underline;
                }
              }
            }

            .stock-info {
              color: #67C23A;
            }

            .service-tags {
              list-style: none;
              padding: 0;
              margin: 0;
              display: flex;
              flex-wrap: wrap;

              li {
                margin-right: 20px;

                i {
                  color: #409EFF;
                  margin-right: 5px;
                }
              }
            }
          }
        }
      }

      .purchase-actions {
        .quantity-selector {
          display: flex;
          align-items: center;
          margin-bottom: 15px;

          .quantity-label {
            margin-right: 10px;
            color: #606266;
            font-size: 14px;
          }

          .unit-text {
            margin-left: 10px;
            color: #909399;
            font-size: 14px;
          }
        }

        .total-price {
          font-size: 14px;
          color: #606266;
          margin-bottom: 20px;

          .price {
            font-size: 18px;
            color: #F56C6C;
            font-weight: bold;
          }
        }

        .action-buttons {
          display: flex;

          .el-button {
            flex: 1;
            padding: 12px 20px;

            & + .el-button {
              margin-left: 15px;
            }
          }
        }
      }
    }

    .right-sidebar {
      .supplier-card, .similar-products, .buyers-list {
        margin-bottom: 20px;

        &::v-deep .el-card__header {
          padding: 15px;
          font-size: 16px;
          font-weight: 600;
          border-bottom: 1px solid #ebeef5;
        }
      }

      .supplier-info {
        text-align: center;

        .supplier-logo {
          width: 80px;
          height: 80px;
          margin: 0 auto 15px;
          background: #f5f7fa;
          border-radius: 4px;
          overflow: hidden;

          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        .supplier-name {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 15px;
        }

        .supplier-stats {
          display: flex;
          border-top: 1px dashed #ebeef5;
          padding-top: 15px;

          .stat-item {
            flex: 1;
            text-align: center;

            .stat-value {
              display: block;
              font-size: 16px;
              font-weight: 600;
              color: #F56C6C;
              margin-bottom: 5px;
            }

            .stat-label {
              display: block;
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }

      .similar-list-container {
        height: 350px;
        overflow-y: auto;
        overflow-x: hidden;

        &::v-deep .el-scrollbar__wrap {
          overflow-x: hidden;
        }

        .buyer-items-container {
          height: 300px;
          overflow-y: auto;
          overflow-x: hidden;
        }

        .similar-item {
          padding: 10px 0;
          cursor: pointer;
          transition: all 0.3s;
          border-bottom: 1px solid #f0f2f5;

          &:last-child {
            border-bottom: none;
          }

          &:hover {
            transform: translateY(-3px);
            background-color: #f5f7fa;
          }

          .similar-image {
            width: 100%;
            height: 120px;
            border-radius: 4px;
            overflow: hidden;
            margin-bottom: 10px;
          }

          .similar-info {
            padding: 0 5px;

            .similar-name {
              font-size: 14px;
              color: #303133;
              margin-bottom: 5px;
              line-height: 1.4;
              height: 40px;
              overflow: hidden;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
            }

            .similar-price {
              color: #F56C6C;
              font-size: 14px;
              font-weight: bold;
            }
          }
        }

        .no-more {
          text-align: center;
          padding: 15px 0;
          color: #909399;
          font-size: 14px;
        }
      }

      .buyer-items {
        height: 300px;

        &::v-deep .el-scrollbar__wrap {
          overflow-x: hidden;
        }

        .buyer-item {
          padding: 12px 0;
          border-bottom: 1px solid #f0f2f5;

          &:last-child {
            border-bottom: none;
          }

          .buyer-header {
            display: flex;
            align-items: center;

            .buyer-avatar {
              background: #409EFF;
              color: #fff;
              margin-right: 12px;
            }

            .buyer-detail {
              flex: 1;

              .company-name {
                font-size: 14px;
                color: #303133;
                margin-bottom: 5px;
              }

              .purchase-time {
                font-size: 12px;
                color: #909399;
              }
            }
          }
        }

        .no-data {
          text-align: center;
          padding: 30px 0;
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }

  .product-detail-tabs {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

    .detail-content {
      padding: 20px;

      .detail-section {
        margin-bottom: 30px;

        &:last-child {
          margin-bottom: 0;
        }

        .section-title {
          font-size: 18px;
          font-weight: 600;
          color: #303133;
          margin: 0 0 15px 0;
          padding-bottom: 10px;
          border-bottom: 1px solid #ebeef5;
        }

        .section-content {
          color: #606266;
          font-size: 14px;
          line-height: 1.6;

          .product-description {
            margin: 0;
            font-family: inherit;
            white-space: pre-wrap;
            word-wrap: break-word;
          }
        }
      }

      .detail-images {
        .detail-image-group {
          margin-bottom: 30px;

          h4 {
            font-size: 16px;
            font-weight: 500;
            color: #606266;
            margin: 0 0 15px 0;
            padding-bottom: 8px;
            border-bottom: 1px dashed #ebeef5;
          }

          .detail-image-item {
            margin-bottom: 15px;

            &:last-child {
              margin-bottom: 0;
            }

            .el-image {
              display: block;
              width: 100%;
              border-radius: 4px;
              overflow: hidden;
              box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            }
          }
        }
      }

      .warranty-section {
        .warranty-item {
          margin-bottom: 20px;

          &:last-child {
            margin-bottom: 0;
          }

          h3 {
            font-size: 16px;
            color: #303133;
            font-weight: 600;
            margin: 0 0 10px 0;

            i {
              color: #409EFF;
              margin-right: 8px;
            }
          }

          p {
            margin: 0 0 8px 26px;
            color: #606266;
            line-height: 1.6;

            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
    }
  }
}

// Order dialog styles
.order-dialog {
  .order-content {
    .order-summary {
      margin-bottom: 20px;

      .summary-header {
        margin-bottom: 15px;

        .title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }
    }

    .order-list-container {
      max-height: 120px;
      margin-bottom: 15px;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 8px;
      border: 1px solid #ebeef5;
      border-radius: 4px;
      background-color: #fff;
    }

    .order-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px;
      background-color: #f8f9fa;
      border-radius: 8px;

      .item-left {
        display: flex;
        align-items: center;

        &:last-child {
          margin-bottom: 0;
        }

        .product-img {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          margin-right: 15px;
        }

        .product-info {
          .product-name {
            font-weight: 500;
            color: #303133;
            font-size: 14px;
            word-break: break-all;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }

      .item-right {
        flex-shrink: 0;

        .quantity {
          color: #409EFF;
          font-weight: 500;
        }
      }
    }

    .address-section {
      margin: 20px 0;

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .title {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
      }

      .address-list {
        .address-radio-group {
          display: flex;
          flex-direction: column;
          gap: 10px;
        }

        .address-radio-item {
          margin: 0;
          padding: 12px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;

          &.is-checked {
            border-color: #409EFF;
            background-color: #ecf5ff;
          }

          .address-info {
            .address-tag {
              margin-bottom: 8px;
            }

            .area-name {
              margin-bottom: 8px;
              color: #303133;
            }

            .area-tag {
              background: #e6e9f0;
              padding: 4px 8px;
              border-radius: 6px;
              font-size: 12px;
              color: #64748b;
            }

            .address-main {
              margin-bottom: 8px;
              color: #303133;
            }

            .address-time {
              font-size: 12px;
              color: #909399;

              i {
                margin-right: 5px;
              }
            }
          }
        }
      }
    }

    .order-footer {
      .total-info {
        .total-item {
          display: flex;
          justify-content: flex-end;
          margin-bottom: 8px;

          .label {
            color: #606266;
          }

          .value {
            margin-left: 10px;

            &.price {
              color: #F56C6C;
              font-weight: bold;
            }
          }
        }
      }
    }
  }
}

// Responsive
@media screen and (max-width: 992px) {
  .product-detail-container {
    .product-main-content {
      .product-gallery {
        .main-image-container {
          height: 350px;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .product-detail-container {
  padding: 15px;

    .product-main-content {
      .product-gallery {
        .main-image-container {
          height: 300px;
        }

        .product-info-panel {
          .purchase-actions {
            .action-buttons {
              flex-direction: column;

              .el-button {
                margin-bottom: 10px;

                & + .el-button {
                  margin-left: 0;
                }
              }
            }
          }
        }
      }
    }
  }


  // 图片错误样式
  .image-error {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f7fa;
    color: #909399;

    i {
      font-size: 32px;
      margin-bottom: 10px;
    }
  }

  .order-list-container {
    max-height: 120px;
    margin-bottom: 15px;
  }

  .order-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 8px;
    margin-bottom: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .product-img {
      width: 70px;
      height: 70px;
      border-radius: 4px;
      margin-right: 12px;
    }

    .product-info {
      .product-name {
        font-weight: 500;
      color: #303133;
        font-size: 14px;
        word-break: break-all;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .item-right {
      flex-shrink: 0;

      .quantity {
        color: #409EFF;
        font-weight: 500;
      }
    }
  }

  .selected-template-info {
    margin-top: 10px;
    padding: 8px;
    background-color: #f0f9eb;
    border-radius: 4px;
    border: 1px solid #e1f3d8;
  }

  /* 设置滚动条样式 */
  .order-list-container::-webkit-scrollbar {
    width: 6px;
  }

  .order-list-container::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;
  }

  .order-list-container::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }

  .empty-tip {
    text-align: center;
    padding: 20px 0;
    color: #909399;
  }

  .address-list-container {
    max-height: 250px;
    overflow-y: auto;
      overflow-x: hidden;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 5px;
  }

  /* 地址列表滚动条样式 */
  .address-list-container::-webkit-scrollbar {
    width: 6px;
  }

  .address-list-container::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;
  }

  .address-list-container::-webkit-scrollbar-track {
    background-color: #f5f7fa;
    }

    .address-radio-group {
      display: flex;
      flex-direction: column;
    gap: 10px;
    }

    .address-radio-item {
      margin: 0;
    padding: 12px;
      border: 1px solid #dcdfe6;
    border-radius: 4px;

      &.is-checked {
        border-color: #409EFF;
        background-color: #ecf5ff;
      }

      .address-info {
        .address-tag {
          margin-bottom: 8px;
        }

        .address-main {
          margin-bottom: 8px;
        color: #303133;
        word-break: break-word;
        }

        .address-time {
          font-size: 12px;
          color: #909399;

        i {
          margin-right: 5px;
        }
      }
    }
  }

  /* 为这些容器添加自定义滚动条样式 */
  .similar-list-container::-webkit-scrollbar,
  .buyer-items-container::-webkit-scrollbar {
    width: 6px;
  }

  .similar-list-container::-webkit-scrollbar-thumb,
  .buyer-items-container::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;
  }

  .similar-list-container::-webkit-scrollbar-track,
  .buyer-items-container::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }
}

// 添加审批流程详情样式
.selected-template-info {
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  background-color: #f0f9eb;

  .template-preview {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px dashed #c2e7b0;

    .template-info {
      margin-bottom: 10px;
      font-size: 13px;
      color: #606266;

      .info-label {
        color: #909399;
        margin-right: 5px;
      }

      .template-desc, .template-type {
        margin-bottom: 5px;
      }
    }

    .nodes-preview {
      .nodes-title {
        display: flex;
        align-items: center;
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 8px;

        i {
          margin-right: 5px;
          color: #409EFF;
        }

        .el-button {
          margin-left: auto;
        }
      }

      .nodes-list {
        max-height: 200px;
        overflow-y: auto;
        background-color: white;
        border: 1px solid #e1f3d8;
        border-radius: 4px;

        .node-item {
          display: flex;
          padding: 8px;
          border-bottom: 1px solid #f0f9eb;

          &:last-child {
            border-bottom: none;
          }

          .node-number {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background-color: #409EFF;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            margin-right: 10px;
          }

          .node-content {
            flex: 1;

            .node-name {
              font-weight: bold;
              margin-bottom: 4px;
            }

            .node-details {
              font-size: 12px;
              color: #909399;
              display: flex;
              flex-wrap: wrap;
              gap: 10px;

              span {
                display: flex;
                align-items: center;

                i {
                  margin-right: 4px;
                }
              }

              .signature-required {
                color: #E6A23C;
              }
            }
          }
        }
      }
    }
  }
}
</style>
